package se.ytterman.jpcap.io;

import java.lang.*;
import java.io.*;
import java.util.*;

import se.ytterman.jpcap.jni.PcapSocket;
import se.ytterman.jpcap.pcap.PcapPacket;

public class PcapPacketOutputStream extends ByteArrayOutputStream {

    public PcapPacketOutputStream(PcapSocket outputSocket) {
	// Store local reference
	this.outputSocket = outputSocket;
    }

    public void flush() throws IOException {
	// "Flush" superclass
	super.flush();

	// Potentially add padding
	this.addPadding(64);

	// Check frame length
	this.checkFrame();

	// Create new packet from byte array
	PcapPacket outputPacket = new PcapPacket(this.toByteArray());

	// Send out to PCAP socket
	this.outputSocket.write(outputPacket);
    }

    private void addPadding(int total_length) {
	// Fetch current buffer length
	int current_length = this.size();

	if(total_length < 0) {
	    // XXX Exception
	}
	else if(total_length < current_length) {
	    // XXX Exception
	} 
	else if(total_length == current_length) {
	    // Do nothing
	}
	else if(total_length > current_length) {
	    // Create padding
	    byte[] padding = new byte[total_length - current_length];
	    int length = padding.length;

	    // Fill with zero
	    for(int i = 0; i < length; i++)
		padding[i] = (byte)0x0;

	    // Add padding
	    this.write(padding, 0, length);
	}
    }

    private void checkFrame() {
	// Fetch current buffer length
	int current_length = this.size();

	// Check frame length
	if(current_length < 64) {
	    // XXX To short
	}
	else if(current_length >= 64 && current_length <= 1514) {
	    // XXX Normal length, excluding CRC
	}
	else if(current_length <= 1514) {
	    // XXX To long
	}
    }

    // Local reference to PCAP socket to write to
    private PcapSocket outputSocket;
}
